package service

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	inits "order_srv/basic/init"
	__ "order_srv/basic/orderproto"
	"order_srv/handler/dao"
	"order_srv/handler/models"
	"order_srv/pkg"
	"order_srv/untils"
	"time"
)

// 取消订单
func (s *Server) CanCelOrder(_ context.Context, in *__.CanCelOrderReq) (*__.CanCelOrderResp, error) {
	id, err := dao.CancelOrders(in)
	if err != nil {
		return nil, err
	}
	return &__.CanCelOrderResp{Id: id}, nil
}

// 已取消订单列表
func (s *Server) IsCanCelOrder(_ context.Context, in *__.IsCanCelOrderReq) (*__.IsCanCelOrderResp, error) {
	fmt.Println("数据", in)
	list, err := dao.CancelOrdersList(in)
	if err != nil {
		return nil, err
	}
	return &__.IsCanCelOrderResp{List: list}, nil
}

// 修改取消订单状态
func (s *Server) OrderCancellationUpdateStatus(_ context.Context, in *__.OrderCancellationUpdateStatusReq) (*__.OrderCancellationUpdateStatusResp, error) {
	if in.Id <= 0 && in.Status <= 0 {
		return nil, errors.New("参数错误")
	}
	status, err := dao.OrderCancellationUpdateStatus(in)
	if err != nil {
		return nil, errors.New(err.Error())
	}

	return &__.OrderCancellationUpdateStatusResp{
		Id: status.Id,
	}, nil
}

// 修改订单司机id
func (s *Server) OrderDriverId(_ context.Context, in *__.OrderDriverIdReq) (*__.OrderDriverIdResp, error) {
	if in.OrderId <= 0 {
		return nil, errors.New("订单ID参数错误")
	}
	if in.DriverId <= 0 {
		return nil, errors.New("司机ID参数错误")
	}
	order, err := dao.OrderDriverId(in)
	if err != nil {
		return nil, errors.New(err.Error())
	}
	return &__.OrderDriverIdResp{
		OrderId: uint64(order.Id),
	}, nil
}

// 订单行动轨迹
func (s *Server) TrajectoryList(_ context.Context, in *__.TrajectoryListReq) (*__.TrajectoryListResp, error) {
	list, err := dao.OrderTrajectory(in)
	if err != nil {
		return nil, err
	}
	o, err := dao.GetOrderLocation(uint32(in.OrderId))
	if err != nil {
		return nil, err
	}
	var distance float64
	distance = untils.CalculateDistance(float64(list[0].Longitude), float64(list[0].Latitude), o.EndLnt, o.EndLat)
	return &__.TrajectoryListResp{
		List:     list,
		Distance: float32(distance),
	}, nil
}

// 记录轨迹经纬度
func (s *Server) RecordLocation(_ context.Context, in *__.RecordLocationReq) (*__.RecordLocationResp, error) {
	err := dao.ReceiveLocationInfo(in)
	if err != nil {
		return nil, err
	}
	return &__.RecordLocationResp{}, nil
}

// 接收位置经纬度放入队列
func (s *Server) ReceiveLocation(_ context.Context, in *__.ReceiveLocationReq) (*__.ReceiveLocationResp, error) {
	queueName := fmt.Sprintf("order_trajectory:%v", in.OrderId)
	var t models.Trajectory
	t.OrderId = uint32(in.OrderId)
	t.Latitude = float64(in.Latitude)
	t.Longitude = float64(in.Longitude)
	t.Point = int8(in.Point)
	data, _ := json.Marshal(&t)
	res, err := inits.NewRabbitMQSimple(queueName).PublishSimple(data)
	if err != nil {
		return nil, err
	}
	if res != true {
		return nil, errors.New("数据传入队列失败")
	}
	return &__.ReceiveLocationResp{}, nil
}

// 订单状态修改
func (s *Server) UpdateOrderStatus(_ context.Context, in *__.UpdateOrderStatusReq) (*__.UpdateOrderStatusResp, error) {
	status, err := dao.UpdateOrderStatus(in)
	if err != nil {
		return nil, fmt.Errorf("修改订单状态失败: %w", err)
	}
	url := ""
	if status.OrderStatus == 4 {
		url = pkg.Alipay(status.OrderSn, fmt.Sprintf("%.2f", status.Price))
	}
	fmt.Println(url)
	return &__.UpdateOrderStatusResp{
		Id:  int64(in.OrderId),
		Url: url,
	}, nil
}

// 经纬度记录
func (s *Server) TrajectorySet(_ context.Context, in *__.TrajectorySetReq) (*__.TrajectorySetResp, error) {
	id, err := dao.RecordLocation(in.OrderId, in.Latitude, in.Longitude, in.Point)
	if err != nil {
		return nil, err
	}
	return &__.TrajectorySetResp{Id: id}, nil
}

// 订单评论
func (s *Server) OrderComment(_ context.Context, in *__.OrderCommentReq) (*__.OrderCommentResp, error) {
	id, err := dao.OrderComment(in)
	if err != nil {
		return nil, err
	}
	return &__.OrderCommentResp{Id: id}, nil
}

// 创建订单
func (s *Server) OrderCreate(_ context.Context, in *__.OrderCreateReq) (*__.OrderCreateResp, error) {
	id, err := dao.OrderCreate(in)
	if err != nil {
		return nil, err
	}
	return &__.OrderCreateResp{Id: uint64(id)}, nil
}

// 紧急求助
func (s *Server) EmergencyHelp(_ context.Context, in *__.EmergencyHelpReq) (*__.EmergencyHelpResp, error) {
	id, err := dao.EmergencyHelp(in)
	if err != nil {
		return nil, err
	}
	// 返回成功状态
	return &__.EmergencyHelpResp{
		Id:     id,
		Status: "pending",
	}, nil
}

// 行程分享
func (s *Server) ShareTrip(_ context.Context, in *__.ShareTripReq) (*__.ShareTripResp, error) {
	id, err := dao.ShareTrip(in)
	if err != nil {
		return nil, err
	}
	// 返回成功状态
	return &__.ShareTripResp{
		Id:     id,
		Status: "success",
	}, nil
}

// 获取保险信息
func (s *Server) GetInsuranceInfo(_ context.Context, in *__.GetInsuranceInfoReq) (*__.GetInsuranceInfoResp, error) {
	resp, err := dao.GetInsuranceInfo(in)
	if err != nil {
		return nil, err
	}
	return resp, nil
}

// 获取用户预约订单列表
func (s *Server) GetUserScheduledOrders(_ context.Context, in *__.GetUserScheduledOrdersReq) (*__.GetUserScheduledOrdersResp, error) {
	list, err := dao.GetUserScheduledOrders(in.UserId)
	if err != nil {
		return nil, err
	}
	return &__.GetUserScheduledOrdersResp{List: list}, nil
}

// 取消预约订单
func (s *Server) CancelScheduledOrder(_ context.Context, in *__.CancelScheduledOrderReq) (*__.CancelScheduledOrderResp, error) {
	err := dao.CancelScheduledOrder(in.OrderId, uint32(in.UserId))
	if err != nil {
		return &__.CancelScheduledOrderResp{Code: 1, Message: err.Error()},
			errors.New("取消预约订单失败" + err.Error())
	}
	return &__.CancelScheduledOrderResp{Code: 0, Message: "取消预约订单成功"}, nil
}

// 订单价格信息添加
func (s *Server) PricingInformationAdd(_ context.Context, in *__.PricingInformationAddReq) (*__.PricingInformationAddResp, error) {
	//参数校验
	if in.OrderId <= 0 {
		return nil, errors.New("订单ID参数错误")
	}
	// 调用数据访问层添加订单价格信息
	p, err := dao.PricingInformationAdd(in)
	if err != nil {
		return nil, err
	}
	return &__.PricingInformationAddResp{Id: p.Id}, nil
}

// 订单价格信息详情
func (s *Server) PricingInformationDetail(_ context.Context, in *__.PricingInformationDetailReq) (*__.PricingInformationDetailResp, error) {
	if in.Id <= 0 {
		return nil, errors.New("订单价格ID参数错误")
	}
	p, err := dao.PricingInformationDetail(in)
	if err != nil {
		return nil, err
	}
	return &__.PricingInformationDetailResp{
		OrderId:         p.OrderId,
		PricesStarting:  float32(p.PricesStarting),
		MileageFee:      float32(p.MileageFee),
		DurationFee:     float32(p.DurationFee),
		LongDistance:    float32(p.LongDistance),
		Bridge:          float32(p.Bridge),
		NightServiceFee: float32(p.NightServiceFee),
		ParkingFee:      float32(p.ParkingFee),
		Other:           float32(p.Other),
		TotalPrice:      float32(p.TotalPrice),
	}, nil
}

// 订单信息详情
func (s *Server) OrderDetail(_ context.Context, in *__.OrderDetailReq) (*__.OrderDetailResp, error) {
	if in.Id <= 0 {
		return nil, errors.New("订单ID参数错误")
	}
	order, err := dao.OrderDetail(in)
	if err != nil {
		return nil, errors.New(err.Error())
	}

	return &__.OrderDetailResp{
		OrderSn:     order.OrderSn,
		OrderType:   int32(order.OrderType),
		UserId:      order.UserId,
		DriverId:    order.DriverId,
		CityId:      order.CityId,
		Price:       float32(order.Price),
		CarTypeId:   int32(order.CarTypeId),
		StartLoc:    order.StartLoc,
		EndLoc:      order.EndLoc,
		PayWay:      int32(order.PayWay),
		Distance:    float32(order.Distance),
		OrderStatus: int32(order.OrderStatus),
	}, nil
}

// 订单时间详情
func (s *Server) OrderTimeDetail(_ context.Context, in *__.OrderTimeDetailReq) (*__.OrderTimeDetailResp, error) {
	if in.Id <= 0 {
		return nil, errors.New("订单ID参数错误")
	}
	order, err := dao.OrderTimeDetail(in)
	if err != nil {
		return nil, errors.New(err.Error())
	}

	DriverDepartTime := order.DriverDepartTime.Format(time.DateTime)
	DriverArriveTime := order.DriverArriveTime.Format(time.DateTime)
	ServiceStartTime := order.ServiceStartTime.Format(time.DateTime)
	ServiceEndTime := order.ServiceEndTime.Format(time.DateTime)
	PayTime := order.PayTime.Format(time.DateTime)
	CancelTime := order.CancelTime.Format(time.DateTime)
	return &__.OrderTimeDetailResp{
		DriverDepartTime: DriverDepartTime,
		DriverArriveTime: DriverArriveTime,
		ServiceStartTime: ServiceStartTime,
		ServiceEndTime:   ServiceEndTime,
		PayTime:          PayTime,
		CancelTime:       CancelTime,
	}, nil
}

// 地址查询经纬度
func (s *Server) AddressLocation(_ context.Context, in *__.AddressLocationReq) (*__.AddressLocationResp, error) {
	// 调用地图API获取路线
	res, err := untils.GetCoordinates(in.Address)
	if err != nil {
		return nil, err
	}

	return &__.AddressLocationResp{
		Lat: float32(res.Result.Location.Lat),
		Lng: float32(res.Result.Location.Lng),
	}, nil
}

// 路线推荐
func (s *Server) RouteRecommend(_ context.Context, in *__.RouteRecommendReq) (*__.RouteRecommendResp, error) {
	// 调用地图API获取路线
	routeResp, err := untils.GetRoute(in.StartAddress, in.EndAddress, int(in.Tactics))
	if err != nil {
		return nil, err
	}

	//转换后的推荐路线响应数据，包含距离、时间和路径点列表
	var way []*__.RouterGet
	// 遍历路线步骤，提取路径点信息
	for _, v := range routeResp.Result.Routes[0].Steps {
		way = append(way, &__.RouterGet{
			Point: v.Path,
		})
	}
	// 构造推荐路线响应，将距离转换为公里，时间转换为小时
	return &__.RouteRecommendResp{
		Distance: float32(routeResp.Result.Routes[0].Distance / 1000),
		MayTime:  float32(routeResp.Result.Routes[0].Duration / 3600),
		List:     way,
	}, nil
}

// 订单支付回调
func (s *Server) OrderPaymentCallback(_ context.Context, in *__.OrderPaymentCallbackReq) (*__.OrderPaymentCallbackResp, error) {
	order := models.Orders{
		OrderSn:     in.OrderSn,
		OrderStatus: int8(in.Status),
	}

	order.PayTime = time.Now()
	err := order.OrderPaymentCallback(order.OrderSn)
	if err != nil {
		return nil, err
	}

	return &__.OrderPaymentCallbackResp{}, nil
}

// 优惠券创建
func (s *Server) CouponTemplateAdd(_ context.Context, in *__.CouponTemplateAddReq) (*__.CouponTemplateAddResp, error) {
	//参数校验
	if in.Title == "" {
		return nil, errors.New("优惠券名称参数错误")
	}
	if in.CouponType <= 0 {
		return nil, errors.New("优惠券类型参数错误")
	}
	if in.Price < 0 {
		return nil, errors.New("优惠券面额参数错误")
	}

	if in.Discount < 0 || in.Discount > 4 {
		return nil, errors.New("优惠券折扣参数错误")
	}
	if in.Limit < 0 || in.Limit > 2 {
		return nil, errors.New("优惠券限定参数错误")
	}
	if in.SpecificCity < 0 || in.SpecificCity > 4 {
		return nil, errors.New("优惠券指定城市参数错误")
	}

	add, err := dao.CouponTemplateAdd(in)
	if err != nil {
		return nil, errors.New("优惠券创建失败" + err.Error())
	}
	return &__.CouponTemplateAddResp{
		Id: add.Id,
	}, nil
}

// 修改改派状态
func (s *Server) UpdateReassignStatus(_ context.Context, in *__.UpdateReassignStatusReq) (*__.UpdateReassignStatusResp, error) {
	//参数校验
	if in.Id <= 0 {
		return nil, errors.New("改派ID参数错误")
	}
	if in.Status <= 0 {
		return nil, errors.New("改派状态参数错误")
	}

	status, err := dao.UpdateReassignStatus(in)
	if err != nil {
		return nil, errors.New("改派状态更新失败" + err.Error())
	}

	return &__.UpdateReassignStatusResp{
		Id: status.Id,
	}, nil
}

func (s *Server) GetUserIdOrderInfo(_ context.Context, in *__.GetUserIdOrderInfoReq) (*__.GetUserIdOrderInfoResp, error) {
	orderList, err := dao.GetUserIdOrderInfo(in)
	if err != nil {
		return nil, errors.New("获取用户订单列表失败" + err.Error())
	}

	return &__.GetUserIdOrderInfoResp{
		List: orderList,
	}, nil
}

// 手动发放用户优惠券添加
func (s *Server) UserCouponAdd(_ context.Context, in *__.UserCouponAddReq) (*__.UserCouponAddResp, error) {
	//参数校验
	if in.UserId <= 0 {
		return nil, errors.New("用户ID参数错误")
	}
	if in.CouponId <= 0 {
		return nil, errors.New("优惠券ID参数错误")
	}

	add, err := dao.UserCouponAdd(in)
	if err != nil {
		return nil, errors.New("用户优惠券添加失败" + err.Error())
	}

	return &__.UserCouponAddResp{
		Id: add.Id,
	}, nil
}

// 用户收藏优惠券
func (s *Server) UserCollectAdd(_ context.Context, in *__.UserCollectAddReq) (*__.UserCollectAddResp, error) {
	//参数校验
	if in.UserId <= 0 {
		return nil, errors.New("用户ID参数错误")
	}
	if in.CouponId <= 0 {
		return nil, errors.New("优惠券ID参数错误")
	}

	add, err := dao.UserCollectAdd(in)
	if err != nil {
		return nil, errors.New("用户收藏优惠券添加失败" + err.Error())
	}

	return &__.UserCollectAddResp{
		Id: add.Id,
	}, nil
}

// 用户分享优惠券添加
func (s *Server) UserShareCouponsAdd(_ context.Context, in *__.UserShareCouponsAddReq) (*__.UserShareCouponsAddResp, error) {
	//参数校验
	if in.SharerId <= 0 {
		return nil, errors.New("用户ID参数错误")
	}
	if in.CouponId <= 0 {
		return nil, errors.New("优惠券ID参数错误")
	}
	if in.ShareToke == "" {
		return nil, errors.New("分享凭证参数错误")
	}
	if in.ExpireTime == "" {
		return nil, errors.New("优惠券过期时间参数错误")
	}

	add, err := dao.UserShareCouponsAdd(in)
	if err != nil {
		return nil, errors.New("用户分享优惠券添加失败" + err.Error())
	}

	return &__.UserShareCouponsAddResp{
		Id: add.Id,
	}, nil
}

// 优惠券展示
func (s *Server) CouponTemplateList(_ context.Context, in *__.CouponTemplateListReq) (*__.CouponTemplateListResp, error) {
	list, err := dao.CouponTemplateList(in)
	if err != nil {
		return nil, errors.New("获取优惠券模板列表失败" + err.Error())
	}

	return &__.CouponTemplateListResp{
		List: list,
	}, nil
}

// 优惠券搜索
func (s *Server) CouponTemplateSearch(_ context.Context, in *__.CouponTemplateSearchReq) (*__.CouponTemplateSearchResp, error) {
	//参数校验
	if in.Title == "" {
		return nil, errors.New("优惠券名称参数错误")
	}
	list, err := dao.CouponTemplateSearch(in)
	if err != nil {
		return nil, errors.New("获取优惠券模板搜索列表失败" + err.Error())
	}
	return &__.CouponTemplateSearchResp{
		List: list,
	}, nil
}

// 优惠券分享添加
func (s *Server) CouponSharesAdd(_ context.Context, in *__.CouponSharesAddReq) (*__.CouponSharesAddResp, error) {
	//参数校验
	if in.CouponId <= 0 {
		return nil, errors.New("优惠券ID参数错误")
	}
	if in.ShareBy <= 0 {
		return nil, errors.New("分享用户ID参数错误")
	}

	add, err := dao.CouponSharesAdd(in)
	if err != nil {
		return nil, errors.New("优惠券分享添加失败" + err.Error())
	}

	return &__.CouponSharesAddResp{
		Id: add.Id,
	}, nil
}
